package com.zaoniao.enstudy.domain.service;

import com.zaoniao.enstudy.domain.entity.ZaoWord;
import com.zaoniao.enstudy.domain.entity.ZaoWordExample;
import com.zaoniao.enstudy.domain.repository.ZaoWordExampleRepository;
import com.zaoniao.enstudy.domain.repository.ZaoWordRepository;
import com.zaoniao.enstudy.infracore.web.PagedGridResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author llb666
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZaoWordService {

    private final ZaoWordRepository zaoWordRepository;

    private final ZaoWordExampleRepository zaoWordExampleRepository;

    /**
     * 根据年级查询年级内10条随机单词.
     *
     * @param grade 年级
     * @param page  第几页
     * @param size  每页数量
     * @return 单词列表
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public PagedGridResult<ZaoWord> getWordListRand(Integer grade, String userId, Integer page, Integer size) {
        PagedGridResult<ZaoWord> wordPagedGridResult = zaoWordRepository.getWordListRand(grade, userId, page, size);
        wordPagedGridResult.getRows().forEach(e -> {
            List<ZaoWordExample> examples = zaoWordExampleRepository.getExamples(e.getWord());
            e.setWordExamples(examples);
        });
        return wordPagedGridResult;
    }

    /**
     * 获取单词详情
     *
     * @param word 单词
     * @return 单词详情信息
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public ZaoWord getWordDetail(String word) {
        ZaoWord zaoWord = zaoWordRepository.getWordDetail(word);
        List<ZaoWordExample> examples = zaoWordExampleRepository.getExamples(word);
        zaoWord.setWordExamples(examples);
        return zaoWord;
    }
}
